<template>
  <div class="p-10" style="background: #fff;">
    <CustomTable
      ref="customTableRef"
      :columns="columns"
      :hasPagination="true"
      :requestInfo="{
        service: '/org', // 请求服务
        serviceUrl: '/org/brand/custom/brand/query', // 请求url
        serviceType: 'post', // 请求方式
      }"
      :extraParams="{
        filters: filters,
      }"
      titleRowAlign="bottom"
      :rowClassName="
        (record, index) => (recordBrand.id == record.id ? 'tableStriped' : '')
      "
      :tableHeight="600"
      :rightButtons="rightButtons"
      :tableConfig="$store.getters.tableConfig"
      tableId="CustomerBrandList"
      @request="$utils.commonRequest"
      :customRow="customRow"
      :hasMoreAction="false"
      @getDictData="getDictData"
      @getListResult="getListResult"
    >
      <template #leftTitle>
        <a-form layout="vertical">
          <a-space :size="20">
            <a-form-item label="品牌名称">
              <a-input
                v-model:value="brand_search_info.brand_name"
                placeholder="请搜索品牌名称"
                class="sear-width"
                @change="changeBrandName"
                allowClear
              />
            </a-form-item>
            <a-form-item label="品牌定位">
              <a-select
                v-model:value="brand_search_info.position"
                class="sear-width"
                placeholder="请选择品牌定位"
                :options="positionOptions"
                @change="changePosition"
                allowClear
              ></a-select>
            </a-form-item>
            <a-form-item label=" ">
              <a-space>
                <a-button type="primary" @click="serchData">搜索</a-button>
                <a-button @click="resettingData">重置</a-button>
              </a-space>
            </a-form-item>
          </a-space>
        </a-form>
      </template>
      <template #buttonIcon-add_brand>
        <PlusOutlined />
      </template>
    </CustomTable>
    <div class="drawer-footer">
      <a-button class="mr-10" @click="onCloseModal">取消</a-button>
      <a-button type="primary" @click="handleOk">确定</a-button>
    </div>
    <!-- 添加品牌 -->
    <AddBrand
      :visible="visiblBrande"
      @success="successBrandChange"
      @onClose="visiblBrande = false"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  onMounted,
  ref,
} from "vue";
import BLCOMMON, { CustomTable } from "bl-common-vue3";
import { PlusOutlined } from "@ant-design/icons-vue";
import AddBrand from "@/views/village/CustomerBrand/modules/AddBrand.vue";
import { useRoute, useRouter } from "vue-router";

export default defineComponent({
  name: "SelectBrandModal",
  components: { CustomTable, PlusOutlined, AddBrand },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    brandId: {
      type: [Number, String],
      default: 0,
    },
  },

  setup(props, { emit }) {
    const route = useRoute();

    const state = reactive({
      recordBrand: {},
      brand_search_info: {},
      filters: [],
      columns: [
        {
          title: "品牌LOGO",
          dataIndex: "brand_logo",
          key: "brand_logo",
          columnType: "image",
          width: 100,
        },
        {
          title: "品牌名称",
          dataIndex: "brand_name",
          key: "brand_name",
          hasSort: true,
          width: 200,
        },
        {
          title: "合作日期",
          dataIndex: "partner_date",
          key: "partner_date",
          width: 100,
        },
        {
          title: "业态",
          dataIndex: "brand_cat_name",
          key: "brand_cat_name",
          width: 300,
        },
        {
          title: "经营方式",
          dataIndex: "brand_info.operation_mode",
          key: "brand_info.operation_mode",
          width: 100,
        },
        {
          title: "品牌定位",
          dataIndex: "brand_info.position",
          key: "brand_info.position",
          columnType: "dictionary",
          dictType: "org_custom_brand_position",
          width: 100,
        },
      ],
      rightButtons: [
        {
          name: "新增",
          key: "add_brand",
          onClick: () => {
            addBrandCategory();
          },
          props: {
            type: "primary",
            disabled: !BLCOMMON.utils.getBtnPermission([
              "customerBrandCategory",
              "curd",
              "add",
            ]),
          },
        },
      ],
      positionOptions: [],
      visiblBrande: false,
    });

    // tab表格实例
    const customTableRef = ref(null);

    // 添加品牌
    const addBrandCategory = () => {
      state.visiblBrande = true;
    };

    const successBrandChange = () => {
      state.visiblBrande = false;
      customTableRef.value.loadData(true);
    };

    //确定
    const handleOk = () => {
      if (window?.microApp?.getData()?.isMainDrawer) {
        window?.microApp?.getData()?.confirm(state.recordBrand);
        window?.microApp?.getData()?.closeModal();
      } else {
        emit("costConfirm", state.recordBrand);
      }
    };

    //取消
    const onCloseModal = () => {
      if (window?.microApp?.getData()?.isMainDrawer) {
        window?.microApp?.getData()?.closeModal();
      } else {
        emit("close");
      }
    };

    const getDictData = (data) => {
      let newArr = []; //定义数组
      for (let key in data.org_custom_brand_position) {
        newArr.push(data.org_custom_brand_position[key]);
      }
      if (newArr.length) {
        state.positionOptions = newArr.map((item) => {
          return {
            label: item.label,
            value: item.value,
          };
        });
      }
    };

    // 自定义行租客
    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };

    // 点击行租客
    const handleTableRowClick = (record) => {
      if (state.recordBrand.id == record.id) {
        state.recordBrand = {};
      } else {
        state.recordBrand = record;
      }
    };

    // 品牌名称
    const changeBrandName = () => {
      if (state.brand_search_info.brand_name) {
        if (!state.filters.find((item) => item.field == "brand_name")) {
          state.filters.push({
            field: "brand_name",
            type: "like",
            value: state.brand_search_info.brand_name,
          });
        }
        state.filters.forEach((item) => {
          if (item.field == "brand_name") {
            item.value = state.brand_search_info.brand_name;
          }
        });
      } else {
        state.filters = state.filters.filter(
          (item) => item.field != "brand_name"
        );
      }
    };

    // 品牌定位
    const changePosition = (key) => {
      if (key != undefined) {
        if (
          !state.filters.find((item) => item.field == "brand_info.position")
        ) {
          state.filters.push({
            field: "brand_info.position",
            type: "like",
            value: key,
          });
        }
        state.filters.forEach((item) => {
          if (item.field == "brand_info.position") {
            item.value = key;
          }
        });
      } else {
        state.filters = state.filters.filter(
          (item) => item.field != "brand_info.position"
        );
      }
    };

    // 搜索
    const serchData = () => {
      customTableRef.value.loadData(true);
    };

    const resettinSearch = () => {
      for (let key in state.brand_search_info) {
        if (key == "brand_name" || key == "partner_date") {
          state.brand_search_info[key] = "";
        }
        if (key == "position") {
          state.brand_search_info[key] = undefined;
        }
      }
      state.filters = [];
    };

    // 重置
    const resettingData = () => {
      resettinSearch();
      customTableRef.value.loadData(true);
    };

    const getListResult = (data) => {
      if (props.brandId || Number(route.query.id) > 0) {
        let brandId = props.brandId || Number(route.query.id);
        state.recordBrand = data?.list.find((item) => item.id == brandId);
      }
    };

    onMounted(() => {});

    return {
      ...toRefs(state),
      customRow,
      handleOk,
      onCloseModal,
      customTableRef,
      serchData,
      resettingData,
      changeBrandName,
      changePosition,
      getDictData,
      addBrandCategory,
      successBrandChange,
      getListResult,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(.tableStriped > td) {
  background-color: #2681f3 !important;
  color: #fff;
}

:deep(.ant-table-tbody > tr.ant-table-row:not(.tableStriped):hover > td) {
  background-color: #d3e3fd;
  color: #000;
}
:deep(.ant-table-tbody tr:nth-child(2n) td) {
  background-color: #fff;
}

.sear-width {
  width: 230px !important;
}

:deep(.ant-form-item) {
  margin: 0 !important;
}
</style>
